package com.lxs.legou.order.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lxs.legou.order.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;

/**
 * @Auther: Mcb
 * @Date: 2022/2/1 22:47
 * @Description: MQ监听，支付状态更改
 */
@Component
public class OrderPayStateListener {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private OrderService orderService;

    @RabbitListener(queues = "${mq.pay.queue.order}")
    public void handlerData(String message){
        Map map = null;
        try {
            map = objectMapper.readValue(message, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        if (map!= null){
            String outTradeNo = (String) map.get("out_trade_no");
            String tradeNo = (String) map.get("trade_no");
            if (map.get("trade_status").equals("TRADE_SUCCESS")){
                //支付状态成功
                orderService.udpatePayState(outTradeNo, tradeNo);
            }else {
                //支付状态失败,删除订单,库存回滚
                orderService.udpatePayStateByError(outTradeNo);
            }
        }

    }
}
